package com.iotproject.studyservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.iotproject.servicebase.exceptionhandler.GlobalException;
import com.iotproject.studyservice.entity.StudyListening;
import com.iotproject.studyservice.entity.StudyListeningType;
import com.iotproject.studyservice.entity.excel.StudyListeningData;
import com.iotproject.studyservice.service.StudyListeningService;
import com.iotproject.studyservice.service.StudyListeningTypeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class StudyListeningExcelListener extends AnalysisEventListener<StudyListeningData> {

    StudyListeningService studyListeningService;
    StudyListeningTypeService studyListeningTypeService;

    public StudyListeningExcelListener() {
    }

    public StudyListeningExcelListener(StudyListeningService studyListeningService, StudyListeningTypeService studyListeningTypeService) {
        this.studyListeningService = studyListeningService;
        this.studyListeningTypeService = studyListeningTypeService;
    }

    @Override
    public void invoke(StudyListeningData studyListeningData, AnalysisContext analysisContext) {
        if (studyListeningData == null) {
            throw new GlobalException(20001, "文件数据为空");
        }
        String name = studyListeningData.getName();
        String content = studyListeningData.getContent();
        String link = studyListeningData.getLink();
        String typeName = studyListeningData.getTypeName();

        QueryWrapper<StudyListeningType> studyListeningTypeQueryWrapper = new QueryWrapper<>();
        studyListeningTypeQueryWrapper.eq("name", typeName);
        StudyListeningType listeningType = studyListeningTypeService.getOne(studyListeningTypeQueryWrapper);
        String typeId = listeningType.getId();

        StudyListening studyListening = exitListening(studyListeningService, name, typeId);
        if (studyListening == null) {
            studyListening = new StudyListening();
            studyListening.setName(name);
            studyListening.setContent(content);
            studyListening.setLink(link);
            studyListening.setTypeId(typeId);
            studyListeningService.save(studyListening);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public StudyListening exitListening(StudyListeningService studyListeningService, String name, String typeId) {
        QueryWrapper<StudyListening> studyListeningQueryWrapper = new QueryWrapper<>();
        studyListeningQueryWrapper.eq("name", name);
        studyListeningQueryWrapper.eq("type_id", typeId);
        StudyListening listening = studyListeningService.getOne(studyListeningQueryWrapper);
        return listening;
    }
}
